package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 线程任务负责与指定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 1. 解析请求
            // 1.1 读取请求行
            String line = readLine();
            System.out.println("请求行：" + line);
            /*String[] data = line.split("\\s");
            String method = data[0];
            String uri = data[1];
            String protocol = data[2];
            System.out.println("请求方式: " + method); // 请求方式
            System.out.println("抽象路径: " + uri); // 抽象路径
            System.out.println("协议版本: " + protocol); // 协议版本
            // 1.2 读取消息头
            while (true) {
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                System.out.println(line);
            }*/

            // 2. 解析消息头
            Map<String, String> headers = new HashMap<>();
            while (true) {
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                System.out.println("消息头：" + line);
                // 每个消息头都按照": "冒号空格拆分为消息头的名字和值并以key value存入headers
                String[] data = line.split(":\\s");
                headers.put(data[0].toLowerCase(), data[1].toLowerCase());
            }
            System.out.println("所有消息头：" + headers);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取客户端发送的一行字符串
     * @return line 客户端发送的一行字符串
     */
    private String readLine() throws IOException{
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a', pre = 'a';
        int d;
        while ((d = in.read()) != -1) {
            cur = (char) d;
            if (pre == 13 && cur == 10) {
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }
}
